//
//  LoginViewController.m
//  CherryPlumStore
//
//  Created by SDX on 2019/9/15.
//  Copyright © 2019 千凯. All rights reserved.
//

#import "LoginViewController.h"
#import <WebKit/WebKit.h>
#import "Config.h"
@interface LoginViewController ()<WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler>
@property (strong, nonatomic) WKWebViewConfiguration *wkWebViewConfiguration;
@property (strong, nonatomic) WKUserContentController *wkUserContentController;
@property (strong, nonatomic) WKWebView *webView;
@end

@implementation LoginViewController

#pragma mark - 设置状态栏颜色
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

#pragma mark - 页面销毁的时候将状态栏字体颜色变回来
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化webview
    [self initWebView];
}

- (void)initWebView {
    // 1. 配置webview
    [self setWkConfiguration];
    // 2. 初始化webview
    _webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:_wkWebViewConfiguration];

    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;

    // 3. 自定义userAgent
    __weak typeof(self) weakSelf = self;
    [_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        __strong typeof (weakSelf) strongSelf = weakSelf;
        NSString *userAgent = result;
        NSString *newUserAgent = [userAgent stringByAppendingString:UA];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dic];
        strongSelf.webView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds];
        // 4. 关闭左划回退功能和上下滑动效果
        strongSelf.webView.allowsBackForwardNavigationGestures = NO;
        strongSelf.webView.scrollView.bounces = NO;

        // 5. 设置url
        NSURL *url = [NSURL URLWithString:WEB_LOGIN_PATH];
        NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:500];
        [strongSelf.webView loadRequest:req];
        [strongSelf.view addSubview:strongSelf.webView];
        // 6. OC注册供JS调用的方法
        [strongSelf addJSFunc];
    }];
}

// 初始化的配置
- (void)setWkConfiguration {
    _wkWebViewConfiguration = [[WKWebViewConfiguration alloc]init];
    WKPreferences *preferences = [[WKPreferences alloc]init];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    _wkWebViewConfiguration.preferences = preferences;
}

// 添加js函数
- (void)addJSFunc {
    _wkUserContentController = [_webView configuration].userContentController;

    [_wkUserContentController addScriptMessageHandler:self name:@"back"];
    [_wkUserContentController addScriptMessageHandler:self name:@"wxLogin"];
    [_wkUserContentController addScriptMessageHandler:self name:@"login"];
}

#pragma mark OC 调用js方法的处理
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // 根据name做想做的操作
    //前端主动JS发送消息，前端指令动作
    if ([@"back" isEqualToString:message.name]) {
        [self back];
    } else if ([@"wxLogin" isEqualToString:message.name]) {
        [self wxLogin];
    } else if ([@"login" isEqualToString:message.name]) {
        [self loginSuccess:message.body];
    }
}

#pragma mark - 返回
- (void)back {
//    [self dismissViewControllerAnimated:YES completion:^{}];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 微信登录
- (void)wxLogin {
    NSLog(@"wxLogin");
    [self back];
}

#pragma mark - 登陆成功 userid token
- (void)loginSuccess:(id)body {
    NSDictionary *dict = body;
    NSString *token = [dict objectForKey:@"token"];
    NSString *userid = [dict objectForKey:@"userid"];
    
    [[NSUserDefaults standardUserDefaults] setValue:token forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setValue:userid forKey:@"userid"];
    [[NSUserDefaults standardUserDefaults] setValue:@YES forKey:@"isLogin"];
    
    [self back];
}

// 页面加载失败的时候调用 delegate方法
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [self back];
}

@end
